package atlub.twitter;

import java.util.ArrayList;
import java.util.List;

import atlub.tweet_crawler.CredentialsRoundrobin;
import atlub.tweet_crawler.ICredentials;
import atlub.tweet_crawler.TwitterAgent;

import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class TweetsCrawler {
    
    Twitter twitter;

    public TweetsCrawler(){
	ICredentials credentials = new CredentialsRoundrobin();
	TwitterAgent agent = new TwitterAgent(credentials.getCredential());
	twitter = agent.getTwitter();
    }
    
    public List<Status> getTweetsByUser(int userId, int limit) throws InterruptedException{
	int curPage = 1;
	int curLimit = limit;
	List<Status> userStatuses = new ArrayList<Status>();
	do{
	    Paging paging = new Paging(curPage, 200);
	    curPage++;
	    curLimit -= 200;
	    
	    while(true){
		try{
		    List<Status> statuses = twitter.getUserTimeline(userId, paging);
		    for(Status s:statuses){userStatuses.add(s);}
		    break;
		}catch(TwitterException e){
		    e.printStackTrace();
		    Thread.sleep(1200*1000);//20 minutes
		}
	    }
	    
	}while(curLimit < 0);
	
	return userStatuses;
    }
    
    public Status getTweetById(int tweetId) throws TwitterException{
	return twitter.showStatus(tweetId);
    }
}
